<template>
  <el-card>
    <div style="display: flex">
      <div style="flex: 1">
        <el-descriptions :title="t('su.product.productInfo')" border>
          <el-descriptions-item :label="t('su.product.code')" align="right">{{ productData.code }}</el-descriptions-item>
          <el-descriptions-item :label="t('su.product.keyword')" align="right">{{ productData.keyword }}</el-descriptions-item>
          <el-descriptions-item :label="t('su.product.unit')" align="right">
            <dict-tag :type="DICT_TYPE.SU_PRODUCT_UNIT" :value="productData.unit" />
          </el-descriptions-item>
          <el-descriptions-item :label="t('su.product.material')" align="right">
            <dict-tag :type="DICT_TYPE.SU_PRODUCT_MATERIAL" :value="productData.material" />
          </el-descriptions-item>
          <el-descriptions-item :label="t('su.product.laser')" align="right">
            <dict-tag :type="DICT_TYPE.SU_PRODUCT_LASER" :value="productData.laser" />
          </el-descriptions-item>
          <el-descriptions-item :label="t('su.product.polish')" align="right">
            <dict-tag :type="DICT_TYPE.SU_PRODUCT_POLISH" :value="productData.polish" />
          </el-descriptions-item>
          <el-descriptions-item :label="t('su.product.dyed')" align="right">
            <dict-tag :type="DICT_TYPE.SU_PRODUCT_DYED" :value="productData.dyed" />
          </el-descriptions-item>
          <el-descriptions-item :label="t('su.product.finishing')" align="right">
            <dict-tag :type="DICT_TYPE.SU_PRODUCT_FINISHING" :value="productData.finishing" />
          </el-descriptions-item>

        </el-descriptions>
      </div>
      <div style="width: 148px; margin-left: 20px">
        <ImgViewer v-model="productData.picUrl" />
      </div>
    </div>

  </el-card>

  <el-card style="margin-top: 20px">
    <template #header>
      <div style="display: flex">
        <span>{{ t('su.product.skuInfo') }}</span>
        <div style="flex: 1"></div>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['su:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.create') }}
        </el-button>
      </div>
    </template>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column :label="t('su.product.property')" align="center" prop="propertyInfo" fixed="left" width="200px"/>
        <el-table-column :label="t('su.product.property')" align="left" prop="property" width="200px" fixed="left">
          <template #default="scope">
            <div v-for="(pro, key) in scope.row.propertyList" :key="key" style="margin-top: 2px">
              <SelectTag pro-key="id" pro-name="name" :list-value="propertyList" :value="pro.code"/>
              <span style="margin-left: 5px">{{ pro.value }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="t('su.product.keyword')" align="center" prop="keyword" />
        <el-table-column :label="t('su.product.salePrice')+'($)'" min-width="100px"  align="center" prop="salePriceUs" />
        <el-table-column :label="t('su.product.salePrice')+'(¥)'" min-width="100px"  align="center" prop="salePriceRmb" />
        <el-table-column :label="t('su.product.purchasePrice') +'($)'" min-width="130px"  align="center" prop="purchasePriceUs" />
        <el-table-column :label="t('su.product.purchasePrice') +'(¥)'"  min-width="130px" align="center" prop="purchasePriceRmb" />
        <el-table-column label="Stock"  min-width="130px" align="center" prop="stock" />
        <el-table-column
          :label="t('table.createTime')"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"

        />
        <el-table-column :label="t('form.operate')" align="center" min-width="120px" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['su:product:update']"
            >
              {{ t('action.edit') }}
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['su:product:delete']"
            >
              {{ t('action.del') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </el-card>

  <el-card style="margin-top: 20px">
    <template #header>
      <div style="display: flex">
        <span>Product Weight</span>
        <div style="flex: 1"></div>
        <el-button
          type="primary"
          plain
          @click="openForm1('create')"
          v-hasPermi="['su:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/> {{ t('action.create') }}
        </el-button>
      </div>
    </template>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="weightList" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="Size" prop="size"/>
        <el-table-column label="Weight" prop="weight"/>
        <el-table-column :label="t('form.operate')" align="center" min-width="120px" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm1('update', scope.row.id)"
              v-hasPermi="['su:product:update']"
            >
              {{ t('action.edit') }}
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete1(scope.row.id)"
              v-hasPermi="['su:product:delete']"
            >
              {{ t('action.del') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
  </el-card>

  <el-card style="margin-top: 20px">
    <template #header>
      <div style="display: flex">
        <span>Proforma Invoice List</span>
        <div style="flex: 1"></div>
      </div>
    </template>

    <ContentWrap>
      <el-table v-loading="piLoading" :data="piList" :stripe="true" :show-overflow-tooltip="true">
        <!--      <el-table-column label=" 编号" align="center" prop="id" />-->
        <el-table-column :label="t('su.invoice.no')" align="center" prop="no" fixed="left" width="200px">
          <template #default="scope">
            <router-link :to="'/su/pi/view/' + scope.row.id">
              <span link type="success">{{ scope.row.no }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column :label="t('su.invoice.status')" align="center" prop="status" fixed="left" width="80px"/>

        <el-table-column :label="t('su.invoice.customer')" align="center" prop="customerId" width="120px">
          <template #default="scope">
            <router-link :to="'/su/pi/customerPi/' + scope.row.customerId">
              <SelectTag pro-key="id" pro-name="name" :list-value="customerList" :value="scope.row.customerId" />
            </router-link>
          </template>
        </el-table-column>
        <el-table-column :label="t('su.invoice.profit') + '$'" align="center" prop="totalProfitUs" width="120px"/>
        <el-table-column :label="t('su.invoice.totalSale') + '$'" align="center" prop="totalSaleUs" width="120px"/>
        <el-table-column :label="t('su.invoice.totalPurhase') + '$'" align="center" prop="totalPurhaseUs" width="120px"/>
        <el-table-column
          :label="t('su.invoice.invoiceDate')"
          align="center"
          prop="invoiceDate"
          :formatter="dateFormatter2"
          width="120px"
        />
        <el-table-column
          :label="t('su.invoice.dueDate')"
          align="center"
          prop="dueDate"
          :formatter="dateFormatter2"
          width="120px"
        />
        <el-table-column :label="t('su.invoice.kind')" align="center" prop="kind" width="120px">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SU_INVOICE_KIND" :value="scope.row.kind" />
          </template>
        </el-table-column>

        <el-table-column :label="t('su.invoice.brand')" align="center" prop="brandId" width="120px">
          <template #default="scope">
            <SelectTag pro-key="id" pro-name="name" :list-value="brandList" :value="scope.row.brandId" />
          </template>
        </el-table-column>
        <el-table-column :label="t('su.invoice.buyer')" align="center" prop="buyer" />
        <el-table-column :label="t('su.invoice.po')" align="center" prop="po" />
        <el-table-column :label="t('su.invoice.payAction')" align="center" prop="payAction" width="120px">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SU_INVOICD_PAY_ACTION" :value="scope.row.payAction" />
          </template>
        </el-table-column>
        <el-table-column :label="t('su.invoice.saler')" align="center" prop="term" />
        <!--        <template #default="scope">-->
        <!--          <dict-tag :type="DICT_TYPE.SU_INVOICE_TERM" :value="scope.row.term" />-->
        <!--        </template>-->
        <!--      </el-table-column>-->
        <el-table-column :label="t('su.invoice.bill')" align="center" prop="bill" />
        <el-table-column :label="t('su.invoice.remarks')" align="center" prop="remarks" />
        <el-table-column :label="t('su.invoice.count')" align="center" prop="count" />
        <el-table-column
          :label="t('table.createTime')"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column :label="t('su.invoice.no')" align="center" min-width="300px" fixed="right">
          <template #default="scope">
            <router-link :to="'/su/pi/view/' + scope.row.id">
              <el-button link type="success">{{ t('action.preview') }}</el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="piTotal"
        v-model:page="piQueryParams.pageNo"
        v-model:limit="piQueryParams.pageSize"
        @pagination="getPiList"
      />
    </ContentWrap>
  </el-card>

  <el-card style="margin-top: 20px">
    <template #header>
      <div style="display: flex">
        <span>Send To Customer</span>
        <div style="flex: 1"></div>
        <el-button
          type="primary"
          plain
          v-print="'#printTest'"
        >
          <Icon icon="ep:plus" class="mr-5px" /> View
        </el-button>
      </div>
    </template>
    <div id="printTest" style="margin: 20px">
      <div style="margin-bottom: 10px">
        <img class="mr-10px h-48px " src="@/assets/imgs/disgosa.png"/>
      </div>
      <div style="display: flex">
        <div style="flex: 1">
          <el-descriptions :title= "'Button Ref:' + productData.code" border>
            <el-descriptions-item :label="t('su.product.unit')" align="right">
              <dict-tag :type="DICT_TYPE.SU_PRODUCT_UNIT" :value="productData.unit" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('su.product.material')" align="right">
              <dict-tag :type="DICT_TYPE.SU_PRODUCT_MATERIAL" :value="productData.material" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('su.product.laser')" align="right">
              <dict-tag :type="DICT_TYPE.SU_PRODUCT_LASER" :value="productData.laser" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('su.product.polish')" align="right">
              <dict-tag :type="DICT_TYPE.SU_PRODUCT_POLISH" :value="productData.polish" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('su.product.dyed')" align="right">
              <dict-tag :type="DICT_TYPE.SU_PRODUCT_DYED" :value="productData.dyed" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('su.product.finishing')" align="right">
              <dict-tag :type="DICT_TYPE.SU_PRODUCT_FINISHING" :value="productData.finishing" />
            </el-descriptions-item>

          </el-descriptions>
        </div>
        <div style="width: 148px; margin-left: 20px">
          <ImgViewer v-model="productData.picUrl" />
        </div>
      </div>
      <div >
        <el-descriptions title="Button Sale Price (PRICE ARE PER 100 PIECES)" border direction="vertical">
          <template v-for="item in list" :key="item.id">
            <el-descriptions-item :label="item.propertyInfo" align="right">${{ Decimal.mul(item.salePriceUs, 100)}}</el-descriptions-item>
          </template>
        </el-descriptions>
      </div>
      <div style="padding-top: 20px">
        <el-descriptions title="Company Information" border>
          <el-descriptions-item label="Name">DISGOSA  ASIA  LIMITED</el-descriptions-item>
<!--          <el-descriptions-item label="Code">DISGOSA  ASIA  LIMITED</el-descriptions-item>-->
          <el-descriptions-item label="Address" :span="3">Room 1305, 13/F Tower A, New Mandarin Plaza, 14 Science Museum Road, Tsim Sha Tsui, Kowloon, Hong Kong</el-descriptions-item>
          <el-descriptions-item label="Contract">Jindy</el-descriptions-item>
          <el-descriptions-item label="Email">sales06@disgosa.com</el-descriptions-item>
          <el-descriptions-item label="Mobile">00.86.188.5737.5894</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </el-card>

  <!-- 表单弹窗：添加/修改 -->
  <ProductSkuForm ref="formRef" @success="getList" />

  <el-dialog title="Weight Info" v-model="showWeight">
    <el-form :model="productWeight">
      <el-form-item label="Size">
        <el-select v-model="productWeight.size">
          <el-option v-for="item in sizes" :key="item" :value="item">{{item}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Weight">
        <el-input placeholder="Weight" v-model="productWeight.weight" clearable/>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div  class="dialog-footer">
        <el-button type="primary" @click="submitWight">Submit</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import { ProductSkuApi, ProductSkuVO } from '@/api/su/productsku'
import { ProductApi } from '@/api/su/product'
import ProductSkuForm from './ProductSkuForm.vue'
import {DICT_TYPE} from "@/utils/dict";
import {CommonApi} from "@/api/su/common";
import {ProformaInvoiceApi} from "@/api/su/pi";
import Decimal from 'decimal.js';
import { ProductWeightApi } from '@/api/su/productweight'
import { number } from 'echarts'
import { string } from 'vue-types'

/** 商品sku 列表 */
defineOptions({ name: 'ProductSku' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute() // 路由

const loading = ref(true) // 列表的加载中
const list = ref<ProductSkuVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  keyword: undefined,
  productId: route.params.productId
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const propertyList = ref([])
const getPropertyList = async () => {
  propertyList.value = await CommonApi.getPropertyList()
}

const customerList = ref([])
const getCompanyList = async () => {
  customerList.value = await CommonApi.getCustomerList()
  getPiList()
}

const productData = ref({
  id: undefined,
  code: undefined,
  picUrl: undefined,
  material: undefined,
  laser: undefined,
  polish: undefined,
  dyed: undefined,
  finishing: undefined,
  keyword: undefined,
  introduction: undefined,
  categoryId: undefined,
  brandId: undefined,
  sliderPicUrls: undefined,
  videoUrl: undefined,
  unit: undefined,
  status: undefined
})

const brandList = ref([])
const getBrandList = async () => {
  brandList.value = await CommonApi.getBrandList()
}

const piLoading = ref(true) // 列表的加载中
const piList = ref<ProductSkuVO[]>([]) // 列表的数据
const piTotal = ref(0) // 列表的总页数
const piQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: route.params.productId
})

const productWeight = ref({
  id: undefined,
  productId: route.params.productId,
  size: undefined,
  weight: 0
})
const weightList = ref<[]>([])
const showWeight = ref(false)
const getWeightList = async () => {
  weightList.value = await ProductWeightApi.getProductWeightList({ productId: route.params.productId });
}

const openForm1 = async (type: string, id?: number) => {
  if(id) {
    productWeight.value = await ProductWeightApi.getProductWeight(id)
  } else {
    productWeight.value = {
      id: undefined,
      productId: route.params.productId,
      size: undefined,
      weight: 0
    }
  }
  showWeight.value = true
}

const submitWight = async () => {
  // productWeight.value.weight = (double) productWeight.value.weight
  if(productWeight.value.id) {
    await ProductWeightApi.updateProductWeight(productWeight.value)
  } else {
    await ProductWeightApi.createProductWeight(productWeight.value)
  }
  showWeight.value = false
  getWeightList()
}

const handleDelete1 = async (id: number) => {
  await ProductWeightApi.deleteProductWeight(id)
  getWeightList()
}

// const print = () => {
//   // this.$print({ selector: '#print-area' });
// }

const getPiList = async () => {
  piLoading.value = true
  try {
    const data = await ProformaInvoiceApi.getProformaInvoicePage(piQueryParams)
    piList.value = data.list
    piTotal.value = data.total
  } finally {
    piLoading.value = false
  }
}

const getProduct = async () => {
  productData.value = await ProductApi.getProduct(route.params.productId)
}

const sizes = ref([])
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductSkuApi.getProductSkuPage(queryParams)
    list.value = data.list
    list.value.forEach(item => {
      item.propertyList = JSON.parse(item.property);
      item.propertyList.forEach((item1) => {
        if(item1.code == 3 && !sizes.value.includes(item1.value)) {
          sizes.value.push(item1.value)
        }
      })
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, queryParams.productId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductSkuApi.deleteProductSku(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSkuApi.exportProductSku(queryParams)
    download.excel(data, '商品sku.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getProduct()
  getPropertyList()
  getList()
  getBrandList()
  getCompanyList()
  getWeightList()
})
</script>

<style>
@media print {
  @page{
    size:  auto;
    margin: 3mm;
  }
}
</style>
